import useStore from '@/store'
import { createRouter, createWebHashHistory, routerKey } from 'vue-router'
import Home from '../views/Home/Home.vue'
import Message from '@/components/XtxMessage'
const router = createRouter({
  scrollBehavior: () => {
    return {
      top: 0
    }
  },
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: () => import('@/views/Layout/Layout.vue'),
      children: [
        {
          path: '', // 默认显示内容
          component: Home
        },
        {
          // 动态路由
          // category/123   ===>
          // category/abc   ===>
          path: 'category/:id', // 默认显示内容
          component: () => import('@/views/Category/Category.vue')
        },
        {
          // 详情页
          path: 'product/:id', // 默认显示内容
          component: () => import('@/views/Goods/Goods.vue')
        },
        {
          // 购物车
          path: 'cart', // 默认显示内容
          component: () => import('@/views/cart/cart.vue')
        },
        {
          // 结算
          path: 'member/checkout', // 默认显示内容
          component: () => import('@/views/Member/Checkout.vue')
        },
        {
          // 支付
          path: '/member/pay',
          component: () => import('@/views/Member/Pay.vue')
        }
      ]

    },
    {
      path: '/login',
      component: () => import('@/views/Login/Login.vue')
    },
    {
      path: '/login/callback',
      component: () => import('@/views/login/callback.vue')
    },
    {
      path: '/Play',
      component: () => import('@/views/Playground.vue')
    }
  ],
})

// 配置路由导航守卫，拦截 /member开头的所有的地址
router.beforeEach((to, from, next) => {
  const { cart } = useStore()
  // 判断用户登没登录
  if (cart.isLogin) {
    next()
  } else {
    if (to.path.includes('/member')) {
      next({
        path: '/login',
        query: {
          redirectUrl: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router